﻿//-----------------------------------------------------------------------
// <copyright file="WebLatestVersionSource.cs" company="AFS">
// Copyright (c) AFS. All rights reserved.
//
//    This file is part of Chatbox.
//
//    Chatbox is free software: you can redistribute it and/or modify
//    it under the terms of the GNU Lesser General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    any later version.
//
//    Chatbox is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//    GNU Lesser General Public License for more details.
//
//    You should have received a copy of the GNU Lesser General Public License
//    along with Chatbox. If not, see http://www.gnu.org/copyleft/lesser.html
// </copyright>

namespace ChatBox.Engine.Web
{
    using System;
    using System.Globalization;
    using System.Threading;
    using System.Xml.Linq;

    using ChatBox.Interfaces;

    using DomainObjects.ResultData;
    using DomainObjects.XmlFeedObjects;

    using Utility;

    /// <summary>
    /// Get the latest client version from the web
    /// </summary>
    public class WebLatestVersionSource : ILatestVersionSource
    {
        #region private

        /// <summary>
        /// the Uri to read
        /// </summary>
        private readonly Uri versionsUri;

        /// <summary>
        /// The thread used
        /// </summary>
        private Thread thread;

        #endregion

        #region constructor

        /// <summary>
        /// Initializes a new instance of the WebLatestVersionSource class 
        /// </summary>
        /// <param name="versionsUri">source for versions data</param>
        public WebLatestVersionSource(Uri versionsUri)
        {
            this.versionsUri = versionsUri;
        }

        #endregion

        #region ILatestVersionSource Members

        /// <summary>
        /// Event handler to call with the result data
        /// </summary>
        public event EventHandler<EventArgs<ClientLatestVersionResult>> Completed;

        /// <summary>
        /// get the latest version data
        /// </summary>
        public void GetLatestVersion()
        {
            this.thread = new Thread(this.ThreadMain);
            this.thread.IsBackground = true;
            this.thread.Name = "Chatbox latest version thread";

            this.thread.Start();
        }

        /// <summary>
        /// The thread main 
        /// </summary>
        private void ThreadMain()
        {
            try
            {
                this.ReadLatestVersion();
            }
            catch (Exception ex)
            {
                // return the error
                this.DoCompleted(new ClientLatestVersionResult(false, "Error posting message", ex));
            }
        }

        /// <summary>
        /// Read the latest version from the server
        /// </summary>
        private void ReadLatestVersion()
        {
            XDocument doc = XDocument.Load(this.versionsUri.ToString());

            var versions = doc.ToClientVersions();
            ClientVersion latestVersion = versions.FindByName("Chatbox");
            string message = string.Format(CultureInfo.InvariantCulture, "Latest version is {0}", latestVersion.LatestVersion);

            this.DoCompleted(new ClientLatestVersionResult(true, latestVersion, message));
        }

        /// <summary>
        /// Fire the completed event
        /// </summary>
        /// <param name="result">the result values to send</param>
        private void DoCompleted(ClientLatestVersionResult result)
        {
            if (this.Completed != null)
            {
                this.Completed(this, new EventArgs<ClientLatestVersionResult>(result));
            }
        }

        #endregion
    }
}
